package com.softeem.iov.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.softeem.iov.dto.R;
import com.softeem.iov.dto.ResponseCode;
import com.softeem.iov.entity.Brand;
import com.softeem.iov.entity.Product;
import com.softeem.iov.mapper.BrandMapper;
import com.softeem.iov.mapper.ProductMapper;
import com.softeem.iov.service.IBrandService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 车辆品牌表 服务实现类
 * </p>
 *
 * @author softeem
 * @since 2023-09-19
 */
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements IBrandService {

    @Autowired
    private ProductMapper productMapper;

    @Override
    public R add(Brand brand) {
        //检查该名称品牌是否存在
        boolean exists = getBaseMapper().exists(Wrappers.query(Brand.class).eq("name",brand.getName()));
        if(exists){
            return R.fail().setMsg("该品牌已存在").setCode(ResponseCode.BRAND_EXISTS_ERR);
        }
        if(save(brand)){
            return R.ok().setMsg("品牌添加成功").setData(brand);
        }
        return R.fail().setMsg("品牌添加失败");
    }

    @Override
    public R update(Brand brand) {
        if(updateById(brand)){
            return R.ok().setMsg("修改品牌成功").setData(getById(brand.getId()));
        }
        return R.ok().setMsg("品牌不存在").setCode(ResponseCode.BRAND_EXISTS_ERR);
    }

    @Override
    public R list(Integer page, Integer limit) {
        IPage<Brand> pageInfo = new Page<>(page,limit);
        List<Brand> list = list(pageInfo);
        pageInfo.setRecords(list);
        return R.ok().setData(pageInfo);
    }

    @Override
    public R removeById(Integer id) {
        //查询该品牌下是否还存在汽车，若存在则无法删除品牌
        Long count = productMapper.selectCount(Wrappers.query(Product.class).eq("bid", id));
        if(count > 0){
            return R.fail().setMsg("该品牌下还有未删除的汽车型号").setCode(ResponseCode.BRAND_DEL_ERR);
        }
        //执行删除
        if(super.removeById(id)){
            return R.ok().setMsg("品牌删除成功");
        }
        return R.fail().setMsg("品牌删除失败");
    }
}
